package com.example.springdemo.controller;

import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import com.example.springdemo.dao.TacoRepository;
import com.example.springdemo.entity.Ingredient;
import com.example.springdemo.entity.Order;
import com.example.springdemo.entity.Taco;
import com.example.springdemo.hateoas.TacoResource;
import com.example.springdemo.hateoas.TacoResourceAssembler;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/design")
@Slf4j
public class DesignTacoController {
    @Resource
    private TacoRepository tacoRepo;

    @ModelAttribute(name = "order")
    public Order order() {
        return new Order();
    }

    @ModelAttribute(name = "design")
    public Taco design() {
        return new Taco();
    }

    @GetMapping("/recent")
    public Resources<TacoResource> recentTacos(){
        PageRequest page = PageRequest.of(0,12, Sort.by("createdAt").descending());
        List<Taco> tacos = tacoRepo.findAll(page).getContent();
        List<TacoResource> tacoResources = new TacoResourceAssembler().toResources(tacos);
        Resources<TacoResource> recentResources = new Resources<>(tacoResources);
        recentResources.add(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(DesignTacoController.class).recentTacos()).withRel("recents"));
        return recentResources;
    }

    @GetMapping("/{id}")
    public Taco getTacoById(@PathVariable("id")Integer id){
        Optional<Taco> optionalIngredient = tacoRepo.findById(id);
        return optionalIngredient.orElseGet(Taco::new);
    }

}
